package com.zxl.openapi.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zxl.openapi.feign.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.Enumeration;
import java.util.Map;

import static com.zxl.openapi.constans.SystemParameter.REDIS_APIPRE;


/**
 * 用于解析用户的请求转发到服务中
 */
@Component
public class RoutingFilter extends ZuulFilter {

    @Autowired
    private RedisService redisService;


    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 100;
    }

    @Override
    public boolean shouldFilter() {
        //如果前面的过滤器返回了false name这个过滤器就不会再执行（提高效率）
        return RequestContext.getCurrentContext().sendZuulResponse();
    }

    @Override
    public Object run() throws ZuulException {
        //按照预先定义好的规则判断用户要去哪
        // 我们规定用户必须通过method参数来传递要请求的接口
        //先获取用户传递的method
        RequestContext currentContext = RequestContext.getCurrentContext();

        HttpServletRequest request = currentContext.getRequest();
        //获取用户传递的请求地址
//        String method = request.getParameter("method");

        //改进！！！！！！   不需要再从redis中查询 直接从currentContext中获取

//            Map<Object, Object> map = redisService.hgetAll(REDIS_APIPRE + method);
        Map<Object,Object> map = (Map<Object, Object>) currentContext.get("apiInfoMap");

        if(map != null && map.size() >=2){
            //获取到了数据
            System.out.println(map);
            //告诉网管要访问那个地址
            currentContext.put(FilterConstants.SERVICE_ID_KEY,map.get("serviceId"));
            String url = (String) map.get("url");
            System.out.println("替换前："+url);
            Enumeration<String> names = request.getParameterNames();
            while (names.hasMoreElements()){
                String name = names.nextElement();
                //正则表达式中{ } 也是特殊符号，需要转义
                url = url.replaceAll("\\{"+name+"\\}",request.getParameter(name));
            }
            System.out.println("替换后："+ url);
            currentContext.put(FilterConstants.REQUEST_URI_KEY, url);
        }else {
            //TODO 此处用改抛出一个异常，返回错误数据给用户；
            currentContext.setResponseBody("method参数不正确");
            //拦截请求
            currentContext.setSendZuulResponse(false);

        }



        return null;

    }
}
